package com.agilerabbit.tools;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.util.Log;

public class KmlParser extends XmlParserRobot {

	@SuppressLint("NewApi")
	private List<KmlPlacemark> getPlacemarksFromXml(String xml) {
		List<KmlPlacemark> retVal = new ArrayList<KmlPlacemark>();
		Document doc = getDomElement(xml);
		NodeList nl = doc.getElementsByTagName("Placemark");
		for (int i = 0; i < nl.getLength(); i++) {
			KmlPlacemark placemark = new KmlPlacemark();

			Element e = (Element) nl.item(i);
			String name = getNodeText(e, "name");
			String description = getNodeText(e, "description");
			String coordinates = getNodeText(e, "Point");
			NodeList points = e.getElementsByTagName("Point");

			for (int x = 0; x < points.getLength(); x++) {
				Coordinate c = new Coordinate();
				Element celement = (Element) points.item(x);
				if (celement != null) {
					String tmpCoord = getNodeText(celement, "coordinates");
					if (!tmpCoord.isEmpty()) {
						String[] parts = tmpCoord.split(",");
						if (parts.length > 1) {
							c.lattitude = parts[0];
							c.longitude = parts[1];
							placemark.points.add(c);
						}
					}
				}

			}

			placemark.name = name;
			placemark.description = description;
			placemark.coordinates = coordinates;
			
			retVal.add(placemark);
		}

		return retVal;
	}

	public List<KmlPlacemark> getPlacemarks(String kmlUrl) {
		String xml = getXmlString(kmlUrl);
		return getPlacemarksFromXml(xml);
	}

}
